package com.bzy.blp.upms.jcaptcha;

import com.bzy.blp.upms.Constants;
import com.bzy.blp.upms.jcaptcha.custom.VerifyCodeUtils;
import com.bzy.common.util.LoggerUtil;
import com.bzy.shiro.util.SessionUtil;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.imageio.ImageIO;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * 生成验证码
 */
public class JCaptchaFilter extends OncePerRequestFilter {

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		String id = request.getRequestedSessionId();
		LoggerUtil.shiroLog("JCaptchaFilter.java--doFilterInternal--session id=" + id);
		
		response.setDateHeader("Expires", 0L);
		response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
		response.addHeader("Cache-Control", "post-check=0, pre-check=0");
		response.setHeader("Pragma", "no-cache");
		response.setContentType("image/jpeg");
		
		if (Constants.USE_JCAPTCHA) {
			BufferedImage bi = JCaptcha.captchaService.getImageChallengeForID(id);
			ServletOutputStream out = response.getOutputStream();
			ImageIO.write(bi, "jpg", out);
			try {
				out.flush();
			} finally {
				out.close();
			}
		} else {
			try {
				// 生成随机字串
				String verifyCode = VerifyCodeUtils.generateVerifyCode(4);
				// 存入Shiro会话session
				SessionUtil.setVerifyCode(verifyCode.toLowerCase());
				// 生成图片
				int w = 146, h = 42;
				VerifyCodeUtils.outputImage(w, h, response.getOutputStream(), verifyCode);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

}
